package controller

import (
	"aqchain/pkg/entity"
	"aqchain/pkg/log"
	"aqchain/pkg/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
)

// GetLicense 获取授权交易状态
func (c *Controller) GetLicense(ctx *gin.Context) {
	var params entity.GetLicenseUri
	err := ctx.BindUri(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	var record model.License
	err = c.db.Where(model.License{DCI: params.DCI}).First(&record).Error
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
		return
	}
	data := entity.License{
		DCI:         record.DCI,
		Seller:      record.Seller,
		BlockNumber: record.BlockNumber,
		Duration:    record.Duration,
		Price:       record.Price,
		Count:       record.Count,
	}
	ctx.JSON(http.StatusOK, SuccessResponse(data))
}

// GetLicenses 获取授权交易状态集合
func (c *Controller) GetLicenses(ctx *gin.Context) {
	var params entity.GetLicensesQuery
	err := ctx.BindQuery(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	var record []entity.License
	db := c.db.Select(
		"items.dci as dci", "seller", "block_number", "price", "duration", "count", "block_time",
		"items.name as name", "items.description as description", "items.category as category").Joins("left join items on licenses.dci = items.dci")

	//按照作品创建时间查询
	if params.IsBlockTimeSearch() {
		begin, end, err := params.Convert()
		if err != nil {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", err.Error()))
			ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
		}
		db = db.Where("licenses.block_time between ? and ?", begin, end)
	}

	//按照作品名称去查找
	if params.IsNameSearch() {
		db = db.Where("name like ?", fmt.Sprintf("%s%s%s", "%", params.Name, "%"))
	}

	//按照作品类型去查找
	if params.IsItemTypeSearch() {
		db = db.Where("category = ?", params.Category)
	}

	if params.IsPagination() {
		db = db.Limit(int(params.PageSize)).Offset(int((params.Current - 1) * params.PageSize))
	}
	db = db.Where(model.License{DCI: params.DCI, Seller: params.Seller})
	err = db.Find(&record).Error
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(err))
		return
	}
	ctx.JSON(http.StatusOK, SuccessResponse(record))
}

// GetLicenseRecords 获取授权记录
func (c *Controller) GetLicenseRecords(ctx *gin.Context) {
	var params entity.GetLicenseRecordsQuery
	err := ctx.BindQuery(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	var records []entity.LicenseRecord
	db := c.db.Select("a3.name", "license_records.tx_hash", "license_records.dci", "license_records.seller",
		"a1.username as sellerUsername", "license_records.buyer", "a2.username as buyerUsername", "license_records.price",
		"license_records.created_time", "from_unixtime(license_records.created_time,'%Y-%m-%d %H:%I:%S') as created_time_string",
		"license_records.deadline", "from_unixtime(license_records.deadline,'%Y-%m-%d %H:%I:%S') as deadline_string",
		"license_records.record_id",
	).
		Joins("left join accounts as a1 on a1.address = license_records.seller").
		Joins("left join accounts as a2 on a2.address = license_records.buyer").
		Joins("left join items as a3 on a3.dci = license_records.dci")
	if params.IsPagination() {
		db = db.Limit(int(params.PageSize)).Offset(int((params.Current - 1) * params.PageSize))
	}
	db = db.Where(model.LicenseRecord{DCI: params.DCI, Seller: params.Seller, Buyer: params.Buyer, RecordID: params.RecordID})
	if params.Deadline > 0 {
		db = db.Where("deadline > ?", params.Deadline)
	}
	err = db.Order("created_time desc").Find(&records).Error
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
		return
	}
	ctx.JSON(http.StatusOK, SuccessResponse(records))
}

// GetLicenseEvents 获取授权操作记录集合
func (c *Controller) GetLicenseEvents(ctx *gin.Context) {
	var params entity.GetLicenseEventsQuery
	err := ctx.BindQuery(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	// 使用 entity.AuctionEvent 接收查询结果
	var events []entity.LicenseEvent
	// 使用Model函数确认查询的表
	db := c.db.Model(&model.LicenseEvent{})
	// 分页
	if params.IsPagination() {
		db = db.Limit(int(params.PageSize)).Offset(int((params.Current - 1) * params.PageSize))
	}
	// 查询条件
	db = db.Where(&model.LicenseEvent{DCI: params.DCI, From: params.Seller, EventName: params.EventName})
	if params.BlockNumber > 0 {
		db = db.Where("blockNumber>?", params.BlockNumber)
	}
	// Join查询关联
	err = db.Find(&events).Error
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
		return
	}
	ctx.JSON(http.StatusOK, SuccessResponse(events))
}

// GetTrades 获取所有交易
func (c *Controller) GetTrades(ctx *gin.Context) {
	var params entity.GetTradesQuery
	err := ctx.BindQuery(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	beginTime, ok := ctx.Get("beginTime")
	if ok {
		log.Logger.Sugar().Debugw("middleware test", "beginTime", beginTime)
	}
	var record []entity.Trade

	subQuery1 := c.db.Table("auctions").Select("dci,block_time,'auctions' as type ")
	subQuery2 := c.db.Table("sales").Select("dci,block_time,'sales' as type ")
	subQuery3 := c.db.Table("licenses").Select("dci,block_time,'licenses' as type ")
	db := c.db.Table("(? UNION ? UNION ? )as al", subQuery1, subQuery2, subQuery3).Select("al.dci,name,description,category,type,block_time").Joins("LEFT JOIN items on al.dci = items.dci")

	//按照作品创建时间查询
	if params.IsBlockTimeSearch() {
		begin, end, err := params.Convert()
		if err != nil {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", err.Error()))
			ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
		}
		db = db.Where("al.block_time between ? and ?", begin, end)
	}

	//按照作品名称去查找
	if params.IsNameSearch() {
		db = db.Where("name like ?", fmt.Sprintf("%s%s%s", "%", params.Name, "%"))
	}
	//按照作品类型去查找
	if params.IsItemTypeSearch() {
		db = db.Where("category = ?", params.Category)
	}
	//按照交易类型去查找
	if params.IsTradeTypeSearch() {
		db = db.Where("type = ?", params.Type)
	}

	if params.IsPagination() {
		db = db.Limit(int(params.PageSize)).Offset(int((params.Current - 1) * params.PageSize))
	}
	err = db.Scan(&record).Error
	for i := 0; i < len(record); i++ {
		record[i].BlockTimeString = time.Unix(int64(record[i].BlockTime), 0).Format("2006-01-02 15:04:05")
	}

	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
		return
	}
	ctx.JSON(http.StatusOK, SuccessResponse(record))
}

//// GetLicenseRecord 查询
//func (c *Controller) GetLicenseRecord(ctx *gin.Context) {
//	var params entity.GetLicenseRecordsQuery
//	err := ctx.BindQuery(&params)
//	if err != nil {
//		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
//		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
//		return
//	}
//	var record entity.LicenseRecord
//	db := c.db.Select("a3.name, license_records.tx_hash, license_records.dci, license_records.type,license_records.seller,a1.username as sellerUsername, license_records.buyer, a2.username as buyerUsername, license_records.price,license_records.created_time, from_unixtime(license_records.created_time,'%Y-%m-%d %H:%I:%S') as created_time_string,license_records.deadline, from_unixtime(license_records.deadline,'%Y-%m-%d %H:%I:%S') as deadline_string").
//		Joins("left join accounts as a1 on a1.address = license_records.seller").
//		Joins("left join accounts as a2 on a2.address = license_records.buyer").
//		Joins("left join items as a3 on a3.dci = license_records.dci").
//		Where(model.LicenseRecord{DCI: params.DCI, Buyer: params.Buyer, Seller: params.Seller,RecordID: params.RecordID}).
//		//Where("license_records.deadline > unix_timestamp(now())").
//		Order("license_records.created_time desc")
//
//	if params.Deadline>0 {
//		db = db.Where("deadline > ?",params.Deadline)
//	}
//
//	err = db.Model(&model.LicenseRecord{}).First(&record).Error
//	if err != nil {
//		if errors.Is(err, gorm.ErrRecordNotFound) {
//			ctx.JSON(http.StatusOK, SuccessResponse(nil))
//			return
//		}
//		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
//		ctx.JSON(http.StatusInternalServerError, ErrorResponse(err))
//		return
//	}
//	ctx.JSON(http.StatusOK, SuccessResponse(record))
//}
